# encoding: utf-8
from config.settings import settings
from loguru import logger
import requests


class TradingCalendarService:
    """交易日历数据服务"""
    
    def __init__(self):
        self.base_url = settings.data_query_host

    def get_trading_calendar(self, start_date=None, end_date=None):
        """
        根据指定的日期范围查询中国股市的交易日历数据
        
        Args:
            start_date (str, optional): 查询开始日期，格式为 YYYY-MM-DD，例如：2024-01-01
            end_date (str, optional): 查询结束日期，格式为 YYYY-MM-DD，例如：2024-01-31
            
        Returns:
            dict: API响应数据，格式如下：
            {
                "code": 200,
                "message": "查询成功",
                "data": [
                    {
                        "trade_date": "2024-01-02"
                    },
                    {
                        "trade_date": "2024-01-03"
                    }
                ],
                "total": 2
            }
        """
        try:
            # 构建请求参数
            params = {}
            if start_date:
                params["start_date"] = start_date
            if end_date:
                params["end_date"] = end_date
            
            # 发送GET请求
            url = f"{self.base_url}/data_query/trading_calendar"
            response = requests.get(
                url,
                params=params,
                timeout=settings.request_timeout_seconds,
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 200:
                    data_count = result.get("total", len(result.get("data", [])))
                    logger.info(f"成功获取交易日历数据，共 {data_count} 条记录")
                    return result
                else:
                    logger.error(f"交易日历API返回错误: {result.get('message', '未知错误')}")
                    return None
            else:
                logger.error(f"交易日历API请求失败，状态码: {response.status_code}")
                return None
                
        except Exception as e:
            logger.exception(f"获取交易日历数据时出错: {e}")
            return None
